package ejb.facade;


import ejb.entities.User;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import ejb.dao.UserDAO;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

@Stateless
public class UserFacadeImp implements UserFacade {

	@EJB
	private UserDAO userDAO;

	@Override
	public void save(User u) {
		userDAO.save(u);
	}

	@Override
	public User update(User u) {
		// TODO Auto-generated method stub
		return userDAO.update(u);
	}

	@Override
	public void delete(User u) {
		// TODO Auto-generated method stub
		userDAO.delete(u);

	}

	@Override
	public User find(int entityID) {
		// TODO Auto-generated method stub
		return userDAO.find(entityID);
	}

	@Override
	public List<User> findAll() {
		// TODO Auto-generated method stub
		return userDAO.findAll();
	}


	@Override
	public User findUserByEmail(String userEmail) {
		return userDAO.findUserByEmail(userEmail);
	}
        
        @Override
	public User findUserByUsername(String username) {
		return userDAO.findUserByUsername(username);
	}

	@Override
	public boolean updatePassword(User u, String oldpwd, String newpwd) {
		if ("".equals(oldpwd) && "".equals(newpwd)) {
			return false;
		}

		if (u.getPassword().equals(oldpwd)) {
			u.setPassword(newpwd);
			userDAO.update(u);
			return true;
		} else {
			return false;
		}
	}

	@Override
	public boolean saveNewUser(User u) {
            String hashedPassword="";
		if (ValidateUser(u)) {
                    try {
                            MessageDigest digest = MessageDigest.getInstance("SHA-256");
                            byte[] hash = digest.digest(u.getPassword().getBytes("UTF-8"));
                            BigInteger bigInt = new BigInteger(1, hash);
                            hashedPassword = bigInt.toString(16);
                    } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
                            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
                    }
			u.setPassword(hashedPassword);
			userDAO.save(u);
			return true;
		} else {
			return false;
		}
	}

        @Override
	public boolean updateUser(User u) {
		if (ValidateUser(u)) {
			userDAO.update(u);
			return true;
		}
		else return false;
	}

	private boolean ValidateUser(User u) {
            //return !"".equals(u.getName()) && !"".equals(u.getSurname()) && !"".equals(u.getDescription()) && !"".equals(u.getPhone()) && !"".equals(u.getEmail()) &&
            //        !"".equals(u.getPassword()) && u.getJob()!= null && !"".equals(u.getUsername());
            return true;
	}

}
